package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {

    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpExprService empExprService;

    @Override
    public PageResult<Emp> getPageResult(EmpQueryParam param) {
       Page<Emp> page = Page.of(param.getPage(),param.getPageSize());
       page.addOrder(OrderItem.asc("update_time"));
       page=page(page);
       List<Emp> emps = page.getRecords();
       List<Integer> empIds = emps.stream().map(emp -> emp.getDeptId()).collect(Collectors.toList());
       List<Dept> depts = deptService.listByIds(empIds);
       emps.forEach(emp -> {
           depts.stream().filter(dept -> dept.getId().equals(emp.getDeptId()))
                   .findFirst().ifPresent(dept -> emp.setDeptName(dept.getName()));
       });
       return new PageResult<>(page.getTotal(),emps);



    }

    @Override
    @Transactional
    public void saveEmp(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());

        save(emp);
        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));
        empExprService.saveBatch(exprList);

    }

    @Override
    public Emp getEmpById(Integer id) {
        Emp byId = getById(id);
        byId.setDeptName(deptService.getById(byId.getDeptId()).getName());
        byId.setExprList(empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId,id)));
        return byId;
    }
}